package controllers

import (
	"github.com/astaxie/beego"
)

type BaseCtl struct {
	beego.Controller
}

func (b *BaseCtl) isLogin() bool {
	if userId := b.GetUserId(); userId > 0 {
		return true
	}
	return false
}

func (b *BaseCtl) GetUserId() (userId int64) {
	iuid := b.GetSession("uid")
	if iuid == nil {
		return
	}

	userId, _ = iuid.(int64)
	return
}

func (b *BaseCtl) SetUserId(userId int64) (err error) {
	b.SetSession("uid", userId)
	return
}

func (b *BaseCtl) DelUserId() {
	b.DelSession("uid")
	return
}

func (b *BaseCtl) SetJson(res interface{}, err error) {
	b.Data["json"] = NewRes(res, err)
	b.ServeJSON()
	return
}

func (b *BaseCtl) Go2Domain() {
	domain := beego.AppConfig.String("domain")
	b.Redirect("http://"+domain, 302)
	return
}

type Info struct {
	Ok      bool   `json:"ok"`
	Message string `json:"message,omitempty"`
}

func NewInfo(err error) (info *Info) {
	info = new(Info)
	if err == nil {
		info.Ok = true
		return
	}

	info.Message = err.Error()
	return
}

type Result struct {
	Data interface{} `json:"data,omitempty"`
	Info *Info       `json:"info"`
}

func NewRes(data interface{}, err error) *Result {
	return &Result{
		Data: data,
		Info: NewInfo(err),
	}
}
